package com.hyq.learn.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author xiaoyuqin
 * @since 2023/9/15
 */
public class TimeUtil {

    private static final Logger logger = LoggerFactory.getLogger(TimeUtil.class);

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static final String RFC_3339_PATTERN = "yyyy-MM-dd'T'HH:mm:ssXXX";

    public static String dateToStr(Date date, String pattern) {
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(date);
    }

    public static Date stringToDate(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat(RFC_3339_PATTERN);
        try {
            return format.parse(dateStr);
        } catch (ParseException parseException) {
            logger.error("error when parse date:{}", dateStr);
        }
        return null;
    }

    public static String formatter(LocalDateTime localDateTime) {
        return DATE_TIME_FORMATTER.format(localDateTime);
    }
}
